package com.woniu.controller;

import com.woniu.pojo.User;
import com.woniu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    private UserService userService;
    @RequestMapping("login")
    public String login(){
        return "login";
    }
    @RequestMapping("main")
    public String main(){
        return "main";
    }
    @RequestMapping("logoutDo")
    public String logoutDo(HttpSession session){
        session.invalidate();
        return "login";
    }
    @RequestMapping("loginDo")
    @ResponseBody
    public Map<String,Object> loginDo(@Validated User user, Errors errors,HttpSession session){
        Map<String,Object> resultMap = new HashMap<>();
        try {
            List<FieldError> fieldErrors = errors.getFieldErrors();

            if(fieldErrors==null||fieldErrors.size()==0) {
                User loginUser = userService.login(user);
                if (loginUser != null) {
                    session.setAttribute("loginUser", loginUser);
                    resultMap.put("result", true);
                } else {
                    resultMap.put("result", false);
                }
            }else{
                resultMap.put("result", false);
                for (FieldError f:fieldErrors) {
                    resultMap.put(f.getField(),f.getDefaultMessage());
                }
            }
        }catch (Exception e){
            resultMap.put("result",false);
        }
        return resultMap;
    }
}
